package main.java.com.lee.juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description TODO
 * @Author winston
 * @DateTime 2022/1/13
 */
public class ConditionTest {
    public static void main(String[] args) throws InterruptedException {
        Thread waitThread = new Thread(new WaitWorker());
        Thread notifyThread = new Thread(new NotifyWorker());
        waitThread.start();
        Thread.sleep(1000);

        notifyThread.start();

        waitThread.join();
        notifyThread.join();
    }

    private static Lock lock = new ReentrantLock();
    private static Condition condition = lock.newCondition();

    static class WaitWorker implements Runnable{

        @Override
        public void run() {
            lock.lock();
            try{
                print("Wait Thread Locked, I will call await.");
                condition.await(5, TimeUnit.SECONDS);
                print("Wait Thread Locked again.");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    static class NotifyWorker implements Runnable{

        @Override
        public void run() {
            lock.lock();
            try{
                print("notify thread locked, I will call the signal");
                condition.signal();
                print("called the notify, But i have not release the Lock");
            }finally {
                lock.unlock();
            }
        }
    }

    static void print(String message) {
        System.out.println(message);
    }

}
